import Vue from 'vue'
import Login from './views/Login.vue'
import NotFound from './views/404.vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Audit from './views/Audit.vue'
import store from './vuex/store'
import { saveRefreshtime, getMenus } from "./api/api";
import util from "./common/js/util";
Vue.use(Router)

var _import = file => require('@/views' + file + '.vue')
const createRouter = () => new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [{
            path: '/login',
            component: Login,
            name: '',
            parentId: '',
            menuId: '',
            hidden: true,

        },
        // { path: '/main', component: Main },
        {
            path: '/',
            component: require => require(Home),
            name: '首页',
            parentId: '',
            menuId: '',
            iconCls: 'el-icon-message', //图标样式class
            NoTabPage: true,
            hidden: true,
            meta: {
                requireAuth: true
            }

        },

        {
            path: '/404',
            component: NotFound,
            name: '',
            parentId: '',
            menuId: '',
            hidden: true,
            meta: {
                requireAuth: false,
                isLold: false,
            }
        },
        {
            path: '*',
            hidden: true,
            parentId: '',
            menuId: '',
            redirect: { path: '/404' }
        },


    ]
});




const router = createRouter()
export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // the relevant part
}
export default router;
var getRouter;

if (!getRouter) {
    if (!getObjArr('Router')) {
        let token = window.localStorage.getItem("Token");
        if (token && token != "undefined" && token != null) {
            getMenus().then((res) => {

                debugger;
                getRouter = res.data;
                // getRouter.push(customRouter);
                // for (var i = 0; i < getRouter.length; i++) {

                //     router.options.routes.push(getRouter[i]);
                // }
                //getRouter = defaultRouter.concat(getRouter);
                saveObjArr('Router', getRouter) //存储路由到localStorage

            });
        }
    } else {
        getRouter = getObjArr('Router') //拿到路由
        getRouter = filterAsyncRouter(getRouter) //过滤路由
        router.addRoutes(getRouter) //动态添加路由
            // for (var i = 0; i < getRouter.length; i++) {

        //     router.options.routes.push(getRouter[i]);
        // }


    }
}
var storeTemp = store;

router.beforeEach((to, from, next) => {
    //验证Token
    let token = window.localStorage.getItem("Token"); {
        if (token != null && token != "undefined") {
            storeTemp.commit("saveToken", window.localStorage.Token)
        }
        // let tokenExpiresTime = window.localStorage.getItem("TokenExpiresTime");
        // if (tokenExpiresTime != null && tokenExpiresTime != "undefined") {
        //     storeTemp.commit("savetokenExpiresTime", window.localStorage.TokenExpiresTime)
        // }

        // saveRefreshtime();
        if (to.meta.requireAuth) {

            if (token && token != "undefined") {
                next();
            } else {
                store.commit("saveToken", "");
                // store.commit("savetokenExpiresTime", "");
                store.commit("saveTagsData", "");
                window.sessionStorage.removeItem('User');
                window.localStorage.removeItem('Router');
                window.sessionStorage.removeItem('UserName');

                next({

                    path: "/login",

                    query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
                });
                window.location.reload()
            }
        } else {

            next();
        }
    }

    //添加动态路由
    {
        if (!getRouter) {
            if (!getObjArr('Router')) {

                if (token && token != "undefined" && token != null) {
                    getMenus().then((res) => {
                        console.info("getMenus");
                        getRouter = res.data;
                        //getRouter = defaultRouter.concat(getRouter);
                        saveObjArr('Router', getRouter) //存储路由到localStorage
                        routerGo(to, next) //执行路由跳转方

                    });
                }
            } else {

                getRouter = getObjArr('Router') //拿到路由
                routerGo(to, next) //执行路由跳转方
            }
        } else {
            if (to.path != '/login') {
                getRouter = getObjArr('Router') //拿到路由

                // routerGo(to, next)//执行路由跳转方法
            }
            next()
        }
    }
});


//localStorage 存储数组对象的方法
function saveObjArr(name, data) {
    localStorage.setItem(name, JSON.stringify(data))
}

//localStorage 获取数组对象的方法
function getObjArr(name) {
    return JSON.parse(window.localStorage.getItem(name) ? window.localStorage.getItem(name) : null);
}

function routerGo(to, next) {
    getRouter = filterAsyncRouter(getRouter); //过滤路由
    resetRouter();
    router.addRoutes(getRouter) //动态添加路由
        //global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
    next({...to, replace: true })
}

function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象

    const accessedRouters = asyncRouterMap.filter(route => {
        if (route.path) {
            if (route.path === '/') { //Layout组件特殊处理
                route.component = Home
            } else {
                route.component = _import(route.path);

            }
        }
        if (route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children)
        }
        return true
    })

    return accessedRouters
}